package com.gamefx.mvc
{
	import com.gamefx.mvc.classes.Notifier;
	import com.gamefx.mvc.classes.Observer;
	
	import flash.events.EventDispatcher;

	/**
	 * View用于控制UI：它将Model中数据显示到UI中去，并关注Model派发出的消息以便刷新UI；它还对UI中的用户行为进行监听，以便派发Notification通知Controller
	 * 
	 * @author hzf
	 * 
	 */
	public class View extends Notifier
	{
		protected var viewName:String;

		protected var viewComponent:Object;
		
		private var interests:Array;
		private var listeners:Array;


		public function View(viewName:String = null, viewComponent:Object = null)
		{
			this.viewName = (viewName != null) ? viewName : Facade.Name(this);
		}

		public function getViewName():String
		{
			return viewName;
		}

		public function setViewComponent(viewComponent:Object):void
		{
			this.viewComponent = viewComponent;
		}

		public function getViewComponent():Object
		{
			return viewComponent;
		}
		
		
		override public function onRegister():void
		{
			super.onRegister();
			interests = [];
			listeners = [];
		}

		override public function onRemove():void
		{
			super.onRemove();
			
			for ( var i:int=0; i<interests.length; i++ ) 
			{
				facade.removeObserver( interests[i], this );
			}
			
			for ( i=0; i<listeners.length; i++ ) 
			{
				(listeners[i].target as EventDispatcher).removeEventListener(listeners[i].type, listeners[i].listener, listeners[i].useCapture);
			}
			
			interests = null;
			listeners = null;
		}

		
		/**
		 * 订阅消息
		 * @param handler
		 * 
		 */
		public function subscribe(notificationName:String, handler:Function):void
		{
			facade.registerObserver(notificationName, new Observer( handler, this ));
			interests.push(notificationName);
		}

		/**
		 * 对UI控件添加事件侦听
		 * 
		 * @param target
		 * @param type
		 * @param listener
		 * @param useCapture
		 * @param priority
		 * @param useWeakReference
		 * 
		 */
		public function handler(target:EventDispatcher, type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void
		{
			target.addEventListener(type, listener, useCapture, priority, useWeakReference);
			listeners.push( {target:target, type:type, listener:listener, useCapture:useCapture} );
		}
	}
}
